﻿using System;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using Looptribe.Moodlin8.Model.Api;
using Windows.UI.Popups;

namespace Looptribe.Moodlin8.ViewModel
{
    public class LoginViewModel : LoadingViewModel
    {
        public event EventHandler LoginCompleted;

        private ServiceCredentials _credentials;
        public ServiceCredentials Credentials
        {
            get { return _credentials; }
            set
            {
                if (_credentials != value)
                {
                    _credentials = value;
                    RaisePropertyChanged("Credentials");
                }
            }
        }

        public ICommand LoginCommand { get; private set; }

        public LoginViewModel()
        {
            LoginCommand = new RelayCommand(ExecuteLogin, CanExecuteLogin);

            _credentials = new ServiceCredentials { ServiceName = ServiceCredentials.Moodlin8ServiceName };
            //N.B. This is the shortname as set in mdl_external_services

            Controller.LoadCredentials(Credentials);

/*#if DEBUG
            if (ServiceCredentials.IsNullOrEmpty(Credentials))
            {
                Credentials.Username = "srosso";
                Credentials.Password = "Moodle_123";
                Credentials.BaseUri = new Uri("http://www.edwi.it/");
                Credentials.ServiceName = "moodlin8"; //N.B. This is the shortname as set in mdl_external_services
            }
#endif*/

            if (LoginCommand.CanExecute(null))
                LoginCommand.Execute(null);
        }

        private bool CanExecuteLogin()
        {
            return !ServiceCredentials.IsNullOrEmpty(Credentials);
        }

        private async void ExecuteLogin()
        {
            IsLoading = true;
            var apiToken = await Controller.GetApiTokenAsync(Credentials);
            IsLoading = false;
            if (String.IsNullOrEmpty(apiToken))
            {
                RunAsync(
                    async () =>
                              {
                                  Controller.RemoveCredentials();
                                  var dialog = new MessageDialog("Wrong username and/or password.");
                                  await dialog.ShowAsync();
                              });
            }
            else
                RunAsync(
                    () =>
                        {
                            OnLoginCompleted(EventArgs.Empty);
                            Controller.GotoHub();
                        });
        }

        protected virtual void OnLoginCompleted(EventArgs e)
        {
            Controller.StoreCredentials(Credentials);
            var evt = LoginCompleted;
            if (evt != null)
                evt(this, e);
        }
    }
}
